package si.cir.util;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import si.cir.entities.UmNovica;

public class UmNoviceHandler extends DefaultHandler{
	
	private List<UmNovica> novice = new ArrayList<UmNovica>();
	private UmNovica obvestilo;
	private String currentElement = "";

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		
		
//		if(qName.equals("naslov"))
//		{
//			obvestilo = new UmNovica();			
//		}
		
		
		
		if(qName.equals("naslov")){
			currentElement = qName;
			obvestilo = new UmNovica();
		}
		
		else if(qName.equals("datum")){
			currentElement = qName;
		}
		
		else if(qName.equals("opis")){
			currentElement = qName;
		}
		
		else if(qName.equals("vsebina")){
			currentElement = qName;
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		if(qName.equals("naslov")){
			currentElement = "";
		}
		
		else if(qName.equals("datum")){
			currentElement = "";
		}
		
		else if(qName.equals("opis")){
			currentElement = "";
		}
		
		else if(qName.equals("vsebina")){
			novice.add(obvestilo);
			currentElement = "";
		}
		
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		
		//currentElement = new String(ch, start, length); 
		if(currentElement.equals("naslov"))
			obvestilo.setNaslov(new String(ch, start, length));
		
		else if(currentElement.equals("datum"))	
			obvestilo.setDatum(new String(ch, start, length));
		
		else if(currentElement.equals("opis")){
			String value = new String(ch, start, length);
			String o = obvestilo.getOpis();
			if(o != null)
				value = o + value;
			obvestilo.setOpis(value);
		}
		
		else if(currentElement.equals("vsebina")){
			String value = new String(ch, start, length);
			String o = obvestilo.getVsebina();
			if(o != null)
				value = o + value;
			obvestilo.setVsebina(value);
		}
	}
	
	public List<UmNovica> getUmNovice(){
		return novice;
	}
}
